import { Alert, Button, InputNumber, Space, Image, Badge, Modal, Form, Input, Table, App } from 'antd'
import React, { useEffect, useRef, useState } from 'react'
import './CashWithdrawal.less'
import { ProTable } from '@ant-design/pro-components'
import { useModel, history, useSearchParams } from '@umijs/max'
import styles from '@/pages/OrderList/OrderList.less'
import { DownloadOutlined, MoneyCollectOutlined } from '@ant-design/icons'
import dayjs from 'dayjs'
import Upload from '@/components/Upload'

const formItemLayout = {
  labelCol: { span: 24 },
  wrapperCol: { span: 24 }
}

const CashWithdrawal = () => {
  const {
    GetWithdrawalRecord,
    GetTransactionTypeCount,
    GetWithdrawList,
    GetMarkCollect,
    GetWithdrawalType,
    AuditWithdrawal
  } = useModel('Withdrawal')
  const { platformType } = useModel('Global')

  const { message } = App.useApp()

  const tableRef = useRef()

  const [currentPage, setCurrentPage] = useState(1) //  当前页码
  const [pageSize, setPageSize] = useState(10) //  每页数量

  const [amountTotal, setAmountTotal] = useState({}) // 交易金额总计

  // tab 选项卡
  const [searchParams] = useSearchParams()
  const [tabActiveKey, setTabActiveKey] = useState(() => {
    return searchParams.get('tab') || 'all'
  })

  const [tabActiveIndex, setTabActiveIndex] = useState(0)
  const [tabsList, setTabsList] = useState([])

  const tabList = [
    {
      key: 'all',
      tab: '全部',
      num: 0,
      index: 0
    },
    {
      key: 'withdrawal_processing',
      tab: '待处理',
      num: 0,
      index: 1
    },
    {
      key: 'withdrawal_success',
      tab: '已完成',
      num: 0,
      index: 2
    },
    {
      key: 'withdrawal_refuse',
      tab: '拒绝提现',
      num: 0,
      index: 3
    }
  ]

  // 提现方式
  const [withdrawalType, setWithdrawalType] = useState([])

  // 审核弹窗
  const [auditModal, setAuditModal] = useState(false)
  const [auditFormRef] = Form.useForm()
  const [picture, setPicture] = useState('') // 上传图片
  const [currentAuditRow, setCurrentAuditRow] = useState({}) // 当前审核行

  // 获取提现方式
  const getWithdrawalType = async () => {
    const res = await GetWithdrawalType()

    let arr = []
    for (const resKey in res) {
      arr.push({
        id: resKey,
        value: res[resKey]
      })
    }

    arr && setWithdrawalType(arr.map(i => [i.id, i.value]))
  }

  // 获取tab数量
  const getTabCount = async () => {
    const res = platformType === 0 ? await GetTransactionTypeCount() : await GetMarkCollect()
    formatTabs(res)
  }

  //  合并数量进tab徽标
  const formatTabs = tabsItem => {
    setTabsList(
      tabList.map(i => ({
        key: i.key,
        tab: (
          <Badge key={i.key} count={tabsItem[i.key]} overflowCount={99999}>
            <div className={styles.tab_pane_line}>{i.tab}</div>
          </Badge>
        )
      }))
    )
  }

  // 处理 tab 切换
  const handleTabActive = key => {
    let index = tabList.findIndex(i => i.key === key)
    setTabActiveIndex(index)
    setTabActiveKey(key)
    setCurrentPage(1)
    tableRef.current.reload()
  }

  // 跳转申请提现
  const handleGotoApplyWithdrawal = () => {
    // 切换路由到 applyWithdrawal
    history.push('/applyWithdrawal')
  }

  // 处理状态审核
  const handleAudit = (row, auditType) => {
    // // 回显数据
    // if (auditType === 'adopt') {
    //   auditFormRef.setFieldsValue({
    //     picture_url: row.pass_reason,
    //     reason_desc: row.pass_remark,
    //   });
    //   setPicture(row.pass_reason);
    // } else {
    //   auditFormRef.setFieldsValue({
    //     picture_url: row.refund_reason,
    //     reason_desc: row.refund_remark,
    //   });
    //   setPicture(row.refund_reason);
    // }

    let params = {
      ...row,
      auditType
    }
    setCurrentAuditRow(params)
    setAuditModal(true)
  }

  // 处理状态审核确认
  const handleAuditConfirm = () => {
    auditFormRef.submit()
  }
  const auditFormFinish = async values => {
    let { id, auditType } = currentAuditRow
    let params = {
      id,
      type: auditType === 'adopt' ? 1 : 2,
      pass_reason: values.picture_url,
      pass_remark: values.reason_desc,

      refund_reason: values.picture_url,
      refund_remark: values.reason_desc
    }
    const res = await AuditWithdrawal(params)
    if (res) {
      message.success('处理成功')
      setAuditModal(false)
      auditFormRef.resetFields()
      tableRef.current.reload()
    }
  }

  // 处理图片上传
  const normFile = e => {
    if (e && e.length) {
      const { value, key } = e[0]
      if (value) {
        return value
      } else {
        return ''
      }
    } else {
      return ''
    }
  }

  const platformColumns = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 60,
      hideInSearch: true
    },
    {
      title: '店铺名称',
      dataIndex: 'shop_name',
      width: 80,
      hideInSearch: true
    },
    {
      title: '提现方式',
      dataIndex: 'type',
      width: 80,
      valueType: 'select',
      valueEnum: new Map(withdrawalType)
    },
    {
      title: '发起金额',
      dataIndex: 'amount',
      hideInSearch: true,
      width: 80,
      render: (text, record) => <div>{text}元</div>
    },
    {
      title: '提现金额',
      hideInTable: true,
      dataIndex: 'amount',
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <InputNumber
            {...rest}
            addonAfter={'元'}
            placeholder={'请输入'}
            onChange={e => {
              form.setFieldsValue({ [item.dataIndex]: e })
            }}
          />
        )
      },
      width: 80
    },
    {
      title: '支付宝账户',
      hideInTable: true,
      dataIndex: 'alipay_account',
      width: 100
    },
    {
      title: '剩余可提现',
      dataIndex: 'residue_withdraw_amount',
      hideInSearch: true,
      width: 100,
      render: (text, record) => <div>{text}元</div>
    },
    {
      title: '交易流水号',
      dataIndex: 'out_trade_no',
      width: 150,
      render: (text, record) => <p style={{ width: '180px', wordWrap: 'break-word' }}>{text}</p>
    },
    {
      title: '收款人账号',
      dataIndex: 'alipay_account',
      width: 100,
    },
    {
      title: '收款人姓名',
      dataIndex: 'alipay_name',
      width: 100
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      // 枚举
      valueEnum: {
        1: {
          text: '待处理',
          status: 'Processing'
        },
        2: {
          text: '已完成',
          status: 'Success'
        },
        3: {
          text: '拒绝提现',
          status: 'Error'
        },
        4: {
          text: '已取消',
          status: 'Error'
        }
      },
      width: 100
    },
    {
      title: '结果查看',
      hideInSearch: true,
      width: 120,
      render: (text, record) => {
        let { status, pass_reason, refund_remark } = record
        return (
          <>
            {status === 2 && <Image width={100} height={100} src={pass_reason} />}

            {status === 3 && <div className={'res_reason'}>原因 : {refund_remark}</div>}

            {status !== 2 && status !== 3 && <div> - </div>}
          </>
        )
      }
    },
    {
      title: '申请时间',
      dataIndex: 'created_at',
      width: 100,
      valueType: 'dateTimeRange',
      render: (text, record) => <p>{record.created_at}</p>,
      search: {
        transform: value => {
          return {
            created_at_start: dayjs(value[0]['$d'] || value[0]).format('YYYY-MM-DD HH:mm:ss'),
            created_at_end: dayjs(value[1]['$d'] || value[1]).format('YYYY-MM-DD HH:mm:ss')
          }
        }
      }
    },
    {
      title: '处理时间',
      dataIndex: 'completed_at',
      hideInSearch: true,
      width: 100,
      render: (text, record) => {
        let { status, completed_at, rejected_at } = record
        return (
          <p>
            {status === 2 && completed_at}
            {status === 3 && rejected_at}
            {status !== 2 && status !== 3 && '-'}
          </p>
        )
      }
    },
    {
      title: '操作人',
      dataIndex: 'staff_name',
      hideInSearch: true,
      width: 100
    },
    {
      title: '操作',
      key: 'option',
      width: 120,
      valueType: 'option',
      fixed: 'right',
      render: (_, row, index, action) => {
        let { status } = row
        return (
          <>
            {status === 1 ? (
              <>
                <Button type='link' key='adopt' onClick={() => handleAudit(row, 'adopt')}>
                  通过
                </Button>
                <Button type='link' danger key='refuse' onClick={() => handleAudit(row, 'refuse')}>
                  拒绝
                </Button>
              </>
            ) : null}
          </>
        )
      }
    }
  ]

  const storeColumns = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 60,
      hideInSearch: true
    },
    {
      title: '提现方式',
      dataIndex: 'type',
      width: 80,
      valueType: 'select',
      valueEnum: new Map(withdrawalType)
    },
    {
      title: '提现金额',
      dataIndex: 'amount',
      width: 80,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <InputNumber
            {...rest}
            addonAfter={'元'}
            placeholder={'请输入'}
            onChange={e => {
              form.setFieldsValue({ [item.dataIndex]: e })
            }}
          />
        )
      }
    },
    {
      title: '交易流水号',
      dataIndex: 'out_trade_no',
      width: 100,
      render: (text, record) => <div style={{ width: '100px', wordWrap: 'break-word' }}>{text}</div>
    },
    {
      title: '支付宝账户',
      hideInTable: true,
      dataIndex: 'alipay_account',
      width: 100
    },
    {
      title: '收款人姓名',
      dataIndex: 'alipay_name',
      width: 100
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      width: 100,
      // 枚举
      valueEnum: {
        1: {
          text: '待处理',
          status: 'Processing'
        },
        2: {
          text: '已完成',
          status: 'Success'
        },
        3: {
          text: '拒绝提现',
          status: 'Error'
        },
        4: {
          text: '已取消',
          status: 'Error'
        }
      }
    },
    {
      title: '处理凭证',
      hideInSearch: true,
      width: 120,
      render: (text, record) => {
        let { status, pass_reason, refund_remark } = record
        return (
          <>
            {status === 2 && <Image width={80} height={80} src={pass_reason} />}

            {status === 3 && <div className={'res_reason'}>原因 : {refund_remark}</div>}

            {status !== 2 && status !== 3 && <div> - </div>}
          </>
        )
      }
    },
    {
      title: '申请时间',
      dataIndex: 'created_at',
      width: 100,
      valueType: 'dateTimeRange',
      render: (text, record) => <p>{record.created_at}</p>
    },
    {
      title: '处理时间',
      dataIndex: 'completed_at',
      hideInSearch: true,
      width: 100,
      render: (text, record) => {
        let { status, completed_at, rejected_at } = record
        return (
          <p>
            {status === 2 && completed_at}
            {status === 3 && rejected_at}
            {status !== 2 && status !== 3 && '-'}
          </p>
        )
      }
    }
  ]

  const columns = platformType === 0 ? platformColumns : storeColumns

  useEffect(() => {
    getWithdrawalType()
  }, [])

  return (
    <div className='cash_withdrawal'>
      <Alert
        className={'alert_money_box'}
        message={
          <Space>
            {platformType === 0 ? (
              <div className='alert_money'>
                <div>
                  未提现总和 : <span>{amountTotal.un_drawn_sum}元</span>
                </div>
                <div>
                  提现冻结中 : <span>{amountTotal.withdrawal_freeze}元</span>
                </div>
                <div>
                  已提现总和 : <span>{amountTotal.withdrawal_success}元</span>
                </div>
                <div>
                  总计 : <span>{amountTotal.withdrawal_sum}元</span>
                </div>
              </div>
            ) : (
              <div className='alert_money'>
                <div>
                  可提现金额 : <span>{amountTotal.withdrawal_available}元</span>
                </div>
                <div>
                  已提现 : <span>{amountTotal.withdrawal_success}元</span>
                </div>
                <div>
                  提现冻结中 : <span>{amountTotal.withdrawal_freeze}元</span>
                </div>
                <div>
                  总计 : <span>{amountTotal.withdrawal_sum}元</span>
                </div>
              </div>
            )}
          </Space>
        }
        type='info'
        showIcon
        banner
      />

      <ProTable
        scroll={{ x: 'max-content' }}
        actionRef={tableRef}
        request={async params => {
          const filters = {
            type: params.type,
            amount: params.amount,
            out_trade_no: params.out_trade_no,
            alipay_account: params.alipay_account,
            alipay_name: params.alipay_name,
            status: tabActiveIndex,
            created_at_start: params.created_at_start,
            created_at_end: params.created_at_end
          }

          const param = {
            page: params.current,
            page_size: params.pageSize,
            ...filters
          }

          setCurrentPage(params.current)
          setPageSize(params.pageSize)

          const res = platformType === 0 ? await GetWithdrawalRecord(param) : await GetWithdrawList(param)
          setAmountTotal(res.other)
          await getTabCount()

          return {
            data: res.data,
            success: true,
            total: res.total
          }
        }}
        pagination={{
          pageSize: pageSize,
          current: currentPage
        }}
        rowKey='id'
        columns={columns}
        toolBarRender={() => {
          return (
            <>
              {platformType === 1 && (
                <Button key={Math.random().toString()} type='primary' onClick={() => handleGotoApplyWithdrawal()}>
                  <MoneyCollectOutlined />
                  我要提现
                </Button>
              )}
              {/*<Button*/}
              {/*  key={Math.random().toString()}*/}
              {/*>*/}
              {/*  <DownloadOutlined />*/}
              {/*  导出数据*/}
              {/*</Button>*/}
            </>
          )
        }}
        search={{
          defaultCollapsed: false,
          labelWidth: 80,
          span: 8
        }}
        toolbar={{
          multipleLine: true,
          tabs: {
            onChange: key => handleTabActive(key),
            activeKey: tabActiveKey,
            items: tabsList
          }
        }}
        summary={pageData => {
          return (
            <>
              <Table.Summary.Row>
                <Table.Summary.Cell index={0}>
                  <div className='summary_cell'>总计</div>
                </Table.Summary.Cell>
                {platformType === 0 ? (
                  <>
                    <Table.Summary.Cell index={1}>-</Table.Summary.Cell>
                    <Table.Summary.Cell index={2}>-</Table.Summary.Cell>
                    <Table.Summary.Cell index={3}>
                      <div className='summary_cell'>{amountTotal.amount_sum} 元</div>
                    </Table.Summary.Cell>
                  </>
                ) : (
                  <>
                    <Table.Summary.Cell index={1}>-</Table.Summary.Cell>
                    <Table.Summary.Cell index={2}>
                      <div className='summary_cell'>{amountTotal.bottom_sum} 元</div>
                    </Table.Summary.Cell>
                  </>
                )}
              </Table.Summary.Row>
            </>
          )
        }}
      />

      {/*分配审核弹窗*/}
      <Modal
        title={'提现申请处理'}
        mask
        open={auditModal}
        onCancel={() => setAuditModal(false)}
        bodyStyle={{ padding: '20px 0' }}
        width={640}
        destroyOnClose
        maskClosable={false}
        footer={
          <>
            <Button onClick={() => setAuditModal(false)}>取消</Button>
            <Button type={'primary'} danger={currentAuditRow.auditType === 'refuse'} onClick={handleAuditConfirm}>
              {currentAuditRow.auditType === 'refuse' ? '拒绝提现' : '审核通过'}
            </Button>
          </>
        }
      >
        <Form form={auditFormRef} onFinish={auditFormFinish} name='auditForm' {...formItemLayout}>
          <Form.Item name='reason_desc' label='原因描述 : ' rules={[{ required: true, message: '请输入原因' }]}>
            <Input placeholder='请输入原因' allowClear />
          </Form.Item>
          <Form.Item
            name={'picture_url'}
            label='上传处理凭证（常为打款截图）：'
            rules={[{ required: true, message: '请上传凭证图片！' }]}
            valuePropName='picture_url'
            getValueFromEvent={normFile}
          >
            <Upload
              formProps={{
                name: 'file',
                listType: 'picture-card'
              }}
              key={'picture'}
              maxCount={1}
              value={picture}
            ></Upload>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}
export default CashWithdrawal
